﻿namespace EasyGo.Data.Repositories
{
    using System.Data;
    using System.Data.Entity;
    using System.Linq;

    using EasyGo.Logic;

    public abstract class RepositoryBase<T, TDbContext> : IRepository<T>
        where T : Entity
        where TDbContext : DbContext
    {
        protected RepositoryBase(TDbContext context)
        {
            this.DbContext = context;
        }

        protected TDbContext DbContext { get; private set; }

        public virtual void Create(T entity)
        {
            this.DbContext.Set<T>().Add(entity);
            this.DbContext.SaveChanges();
        }

        public virtual void Update(T entity)
        {
            this.DbContext.Entry(entity).State = EntityState.Modified;
            this.DbContext.SaveChanges();
        }

        public virtual T Load(int id)
        {
            return this.DbContext.Set<T>().Find(id);
        }

        public virtual IQueryable<T> GetAll()
        {
            return this.DbContext.Set<T>();
        }

        public virtual void Delete(T entity)
        {
            this.DbContext.Set<T>().Remove(entity);
            this.DbContext.SaveChanges();
        }

        public virtual void SaveChanges()
        {
            this.DbContext.SaveChanges();
        }
    }
}
